
<template>
    <div class="drawerClass">
        <template v-if="props.type=='drawer'">
            <el-drawer  close-on-press-escape title="高级查询" v-model="drawerShow" direction="rtl" size="800px"
                :destroy-on-close="true" @close='closeDrawer' :wrapperClosable='true'>

                <el-tabs style="margin-left: 10px;" v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="查询条件" name="First">
                        <div class="flex flex-col">
                            <div style="padding: 5px 0px;" class="flex justify-between">
                                <div class="flex justify-center">

                                    <el-dropdown @command="handleCommand" class="flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer">
                                        <span class="inline-block text-white w-full px-1.5 text-left">
                                            <el-icon><ArrowDown /></el-icon>&nbsp;选择方案
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item v-for="(item, index) in solutionList" :key="index"
                                                    :command="item.CID">
                                                    <i :style="{ 'color': item.CID == currentSolutionCID ? 'green' : '' }"
                                                        :class="[item.CID == currentSolutionCID ? 'vxe-icon-check' : 'vxe-icon-minus']"></i>
                                                    <span :style="{ 'color': !!item.CDEFAULT ? 'red' : '' }"> {{ item.CSCHEME_NAME
                                                    }}</span>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>

                                </div>
                                <div style="margin-right: 10px;">
                                    <el-button :loading="loading_PostSearchBtn" @click="queryFunc()" type="primary">
                                        <el-icon><Search /></el-icon>&nbsp;查询
                                    </el-button>
                                    <el-button @click="resetQuery()" type="warning">
                                        <el-icon><RefreshRight /></el-icon>&nbsp;重置
                                    </el-button>
                                
                                </div>
                            </div>

                            <div>
                                <TableTemplate ref="TableFirstTemplateRef" :conditionConfig="addFlag"
                                    :isClearTreeData='isClearTreeData' :tableOptions="tableData"
                                    :tableDataLoading="tableDataLoading" :isAdd='isAdd' @handleEnterEvent="handleEnterEvent" />
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="新增方案" name="Second">
                        <div class="flex flex-col">
                            <div style="padding: 5px 0px;" class="flex justify-between">
                                <div class="flex justify-center">


                                    <el-dropdown @command="handleNewCommand" class="flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer">
                                        <span class="inline-block text-white w-full px-1.5 text-left">
                                            <el-icon><ArrowDown /></el-icon>&nbsp;选择方案
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item v-for="(item, index) in solutionList" :key="index"
                                                    :command="item.CID">
                                                    <i :style="{ 'color': item.CID == solutionCID ? 'green' : '' }"
                                                        :class="[item.CID == solutionCID ? 'vxe-icon-check' : 'vxe-icon-minus']"></i>
                                                    <span :style="{ 'color': !!item.CDEFAULT ? 'red' : '' }"> {{ item.CSCHEME_NAME
                                                    }}</span>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-dropdown :disabled="isDisabledCommandBtn && !!solutionCID" @command="addProgramme"
                                        class="flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer">
                                        <span class="inline-block  text-white w-full px-1.5 text-left">
                                            <el-icon><ArrowDown /></el-icon>&nbsp;新增条件
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="group">条件组</el-dropdown-item>
                                                <el-dropdown-item command="condition">条件</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-button type="warning" @click="clearClick()">
                                        <el-icon><Refresh /></el-icon>清空
                                    </el-button>
                                    <el-button :disabled="(isDisabledDeleteBtn)" @click="removeConditionClick()"
                                        v-show="!!solutionCID" type="danger" :loading="deleteBtnLoading">
                                        <el-icon><Delete /></el-icon>&nbsp;删除
                                    </el-button>
                                    <el-button :disabled="(isDisabledSaveBtn && !!solutionCID)" @click="submitEditDialog()"
                                        :loading="submitBtnLoading" type="success">
                                        <i class="vxe-icon-save"></i>&nbsp; 
                                        <span  v-show="!solutionCID">新增</span>
                                        <span  v-show="!!solutionCID">更新</span>
                                    </el-button>
                                </div>
                                <div style="margin-right: 10px;">
                                
                                </div>
                            </div>
                            <div style="margin-top: 10px;">
                                <el-form ref="searchSolutionRef" :inline="true" :rules="rulesSolution" :model="formSolution">
                                    <el-form-item label="方案名称" prop="name">
                                        <el-input :readonly="(isDisabledSaveBtn && !!solutionCID)" style="width: 160px"
                                            v-model="formSolution.name" placeholder="方案名称" clear></el-input>
                                    </el-form-item>
                                    <el-form-item label="可见性" prop="region">
                                        <el-select disabled :userId="userInfo?.CID" style="width: 160px"
                                            v-model="formSolution.region" placeholder="请选择可见性">
                                            <el-option label="仅有我" :value="userInfo?.CID" />
                                            <el-option label="全局" :value="0" />

                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="设为默认">
                                        <el-checkbox 
                                            v-model="formSolution.defaultOption"></el-checkbox>
                                    </el-form-item>
                                </el-form>
                            </div>
                            <div>
                                <TableSecondTemplate ref="TableSecondTemplateRef" :conditionConfig="addFlag" :isClearTreeData='isClearTreeData'
                                    :solutionList="solutionList" :optionModel="optionModel" :formSolution="formSolution"
                                    @formDataChangeFn="formDataChangeFn" @disabledDeleteBtnFn="disabledDeleteBtnFn"
                                    @submitSuccess="submitSuccessFn" @submitBtnLoadingFn="submitBtnLoadingFn"
                                    :solutionCID="solutionCID" />
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-drawer>
        </template>
        <template v-else>
            <el-tabs style="margin-left: 10px;" v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="查询条件" name="First">
                        <div class="flex flex-col">
                            <div style="padding: 5px 0px;" class="flex justify-between">
                                <div class="flex justify-center">

                                    <el-dropdown @command="handleCommand" class="flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer">
                                        <span class="inline-block text-white w-full px-1.5 text-left">
                                            <el-icon><ArrowDown /></el-icon>&nbsp;选择方案
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item v-for="(item, index) in solutionList" :key="index"
                                                    :command="item.CID">
                                                    <i :style="{ 'color': item.CID == currentSolutionCID ? 'green' : '' }"
                                                        :class="[item.CID == currentSolutionCID ? 'vxe-icon-check' : 'vxe-icon-minus']"></i>
                                                    <span :style="{ 'color': !!item.CDEFAULT ? 'red' : '' }"> {{ item.CSCHEME_NAME
                                                    }}</span>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>

                                </div>
                                <div style="margin-right: 10px;">
                                    <el-button :loading="loading_PostSearchBtn" @click="queryFunc()" type="primary">
                                        <el-icon><Search /></el-icon>&nbsp;查询
                                    </el-button>
                                    <el-button @click="resetQuery()" type="warning">
                                        <el-icon><RefreshRight /></el-icon>&nbsp;重置
                                    </el-button>
                                
                                </div>
                            </div>

                            <div>
                                <TableTemplate ref="TableFirstTemplateRef" :conditionConfig="addFlag"
                                    :isClearTreeData='isClearTreeData' :tableOptions="tableData"
                                    :tableDataLoading="tableDataLoading" :isAdd='isAdd' @handleEnterEvent="handleEnterEvent" />
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="新增方案" name="Second">
                        <div class="flex flex-col">
                            <div style="padding: 5px 0px;" class="flex justify-between">
                                <div class="flex justify-center">


                                    <el-dropdown @command="handleNewCommand" class="flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer">
                                        <span class="inline-block text-white w-full px-1.5 text-left">
                                            <el-icon><ArrowDown /></el-icon>&nbsp;选择方案
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item v-for="(item, index) in solutionList" :key="index"
                                                    :command="item.CID">
                                                    <i :style="{ 'color': item.CID == solutionCID ? 'green' : '' }"
                                                        :class="[item.CID == solutionCID ? 'vxe-icon-check' : 'vxe-icon-minus']"></i>
                                                    <span :style="{ 'color': !!item.CDEFAULT ? 'red' : '' }"> {{ item.CSCHEME_NAME
                                                    }}</span>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-dropdown :disabled="isDisabledCommandBtn && !!solutionCID" @command="addProgramme"
                                        class="flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer">
                                        <span class="inline-block  text-white w-full px-1.5 text-left">
                                            <el-icon><ArrowDown /></el-icon>&nbsp;新增条件
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item command="group">条件组</el-dropdown-item>
                                                <el-dropdown-item command="condition">条件</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-button type="warning" @click="clearClick()">
                                        <el-icon><Refresh /></el-icon>清空
                                    </el-button>
                                    <el-button :disabled="(isDisabledDeleteBtn)" @click="removeConditionClick()"
                                        v-show="!!solutionCID" type="danger" :loading="deleteBtnLoading">
                                        <el-icon><Delete /></el-icon>&nbsp;删除
                                    </el-button>
                                    <el-button :disabled="(isDisabledSaveBtn && !!solutionCID)" @click="submitEditDialog()"
                                        :loading="submitBtnLoading" type="success">
                                        <i class="vxe-icon-save"></i>&nbsp; 
                                        <span  v-show="!solutionCID">新增</span>
                                        <span  v-show="!!solutionCID">更新</span>
                                    </el-button>
                                </div>
                                <div style="margin-right: 10px;">
                                
                                </div>
                            </div>
                            <div style="margin-top: 10px;">
                                <el-form ref="searchSolutionRef" :inline="true" :rules="rulesSolution" :model="formSolution">
                                    <el-form-item label="方案名称" prop="name">
                                        <el-input :readonly="(isDisabledSaveBtn && !!solutionCID)" style="width: 160px"
                                            v-model="formSolution.name" placeholder="方案名称" clear></el-input>
                                    </el-form-item>
                                    <el-form-item label="可见性" prop="region">
                                        <el-select disabled :userId="userInfo?.CID" style="width: 160px"
                                            v-model="formSolution.region" placeholder="请选择可见性">
                                            <el-option label="仅有我" :value="userInfo?.CID" />
                                            <el-option label="全局" :value="0" />

                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="设为默认">
                                        <el-checkbox 
                                            v-model="formSolution.defaultOption"></el-checkbox>
                                    </el-form-item>
                                </el-form>
                            </div>
                            <div>
                                <TableSecondTemplate ref="TableSecondTemplateRef" :conditionConfig="addFlag" :isClearTreeData='isClearTreeData'
                                    :solutionList="solutionList" :optionModel="optionModel" :formSolution="formSolution"
                                    @formDataChangeFn="formDataChangeFn" @disabledDeleteBtnFn="disabledDeleteBtnFn"
                                    @submitSuccess="submitSuccessFn" @submitBtnLoadingFn="submitBtnLoadingFn"
                                    :solutionCID="solutionCID" />
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
        </template>
       
    </div>
</template>
<script setup>
import VXETable from 'vxe-table'
import { getCookie, getLocalStorageStore } from '@/libs/setStore.js'
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
// import { useRoute } from 'vue-router'
// import { useStore } from 'vuex'
import axios from "@/libs/request.js";
import dayjs from 'dayjs';
import TableTemplate from './tableTemplate/index.vue'
import TableSecondTemplate from './tableTemplate/second.vue'
// 导入 Element Plus 图标
import { ArrowDown, Search, RefreshRight, Refresh, Delete } from '@element-plus/icons-vue'

// 定义组件名称
defineOptions({
    name: 'drawerComponent'
})

// 定义 props
const props = defineProps({
    // 仅 type='tabs' 时，查询配置信息
    config: {
        type: Object,
        default() {
            return {
                cleanCache:false,
                tableId: null,
                CPARENT: '',
                closeAfterSearchPro:true
            }
        }
    },
    // 新增 类型
    type: {
        type: String,
        default: 'drawer' // drawer | tabs
    }
})
// 定义 emits
const emit = defineEmits(['update:drawerShow', 'queryFunc'])

// 组合式API
// const route = useRoute()
let fullURL = window.location.href
// const store = useStore()

// 响应式数据
const cacheDataObj = ref({
    // [$fullURL]:{searchParams:{},solutionList:[],lastTimeSearchSolutionCID:null}
}) // 缓存列表
const searchTimer = ref(null)
const loading_PostSearchBtn = ref(false) // 查询按钮是否进行中...
const currentSolutionCID = ref(null) // 查询条件页面，当前选中方案
const solutionCID = ref(null) // 当前选中的解决方案ID【新增方案页面】
const isDisabledDeleteBtn = ref(false) // 是否禁用删除按钮
const isDisabledSaveBtn = ref(false) // 是否禁用保存按钮
const isDisabledCommandBtn = ref(false) // 是否禁用新增条件按钮
const solutionList = ref([]) // 方案列表
const submitBtnLoading = ref(false)
const deleteBtnLoading = ref(false) // 是否删除进行中...
const optionModel = ref(null)
const activeName = ref("First")
const tableDataLoading = ref(false) // 表格数据加载中...
const drawerShow = ref(false)
const isTure = ref(false)
const modelVisible = ref(false)
const isClearTreeData = ref(0)
const searchProTableID = ref('')
const searchProSettingCPARENT = ref("")
const tableData = ref([])
const loadDataConfig = ref(null)
const isAdd = ref(false)
const addFlag = reactive({
    hash: '',
    flag: ''
})
const formSolution = reactive({
    name: '',
    region: 0,
    defaultOption: false
})
const rulesSolution = reactive({
    name: [
        { required: true, message: '请输入方案名称', trigger: 'blur' },
    ],
})

// 模板引用
const searchSolutionRef = ref(null)
const TableFirstTemplateRef = ref(null)
const TableSecondTemplateRef = ref(null)

// 计算属性
const multiOrganization = ref(getLocalStorageStore('multiOrganization'))
const userInfo = ref(getLocalStorageStore('userInfo') || getCookie('userInfo') || { CID: null })
// const userInfo = computed(() => store.getters.userInfo)
// const multiOrganization = computed(() => store.getters.multiOrganization)
onMounted(() => {
    if(props.type=='tabs'){
         searchProTableID.value = props.config.tableId
         optionModel.value = {
            searchProSettingCPARENT: props.config.CPARENT,
            searchProSettingID: props.config.tableId,
            cleanCache: props.config.cleanCache || false,
            closeAfterSearchPro: props.config.closeAfterSearchPro,
        }
        nextTick(() => {
            // 方案列表
                loadSolutionList(optionModel.value.cleanCache)
        })
    }
})
// 生命周期
onUnmounted(() => {
    // 清除缓存数据
    cacheDataObj.value = {}
})
// 方法定义
/**
 * 打开弹框 外部 ref 调用该方法传参
 * data: {
 *      drawerShow: true, // 打开弹框条件
 *      tableId: 0  //  必填，表格id
 *      CPARENT: 0, // 必填 ，父级ID
 *      cleanCache:true,//测试清空缓存
 *      closeAfterSearchPro   搜索后是否关闭 true/false
 * }
 * **/
const openDrawer = (data) => {
    //debugger
    if(!data.tableId){
         VXETable.modal.message({message:"未配置高级搜索ID", status:'error' })
         return
    }
    searchProTableID.value = data.tableId
    optionModel.value = {
        searchProSettingCPARENT: data.CPARENT,
        searchProSettingID: data.tableId,
        cleanCache: data.cleanCache || false,
        closeAfterSearchPro: data.closeAfterSearchPro,
    }
    drawerShow.value = true
    nextTick(() => {
        // 方案列表
            loadSolutionList(optionModel.value.cleanCache)
    })
}

// 设置时间范围格式默认值 (当前日期:curdate 当前日期-1月:subtract-1-month  当前日期+1天:add-1-day  当前日期-1年:add-2-year)
const setDateTimeRangeDefaultVal = (type, defaultVal) => {
    const end = new Date();
    const start = new Date();

    try {
        let dValue = [start, end]
        let dateFormatStr = ""
        let defaultValList = defaultVal.split('#')
        // 指定日期 格式化 格式
        switch (type) {
            case "daterange":
                dateFormatStr = 'YYYY-MM-DD'
                break;
            case "datetimerange":
                dateFormatStr = 'YYYY-MM-DD HH:mm:ss'
                break;
            default:
                dateFormatStr = ""
                break
        }
        // 开始时间 和 结束时间
        // curdate#curdate
        if (!!defaultValList[0]) {
            if (defaultValList[0] == 'curdate') {
                // 当前日期
                dValue[0] = dayjs().format(dateFormatStr);
            } else if (defaultValList[0].includes('-')) {
                // 指定日期加减
                //dayjs().add(7, 'day').format('YYYY-MM-DD');
                //dayjs().subtract(2, 'hour').format('YYYY-MM-DD HH:mm:ss');
                let daysetArray = defaultValList[0].split('-')
                dValue[0] = dayjs()[daysetArray[0]](Number(daysetArray[1]), daysetArray[2]).format(dateFormatStr)
            } else {
                //空日期
                dValue[0] = start
            }
        }
        if (!!defaultValList[1]) {
            if (defaultValList[1] == 'curdate') {
                // 当前日期
                dValue[1] = dayjs().format(dateFormatStr);
            } else if (defaultValList[1].includes('-')) {
                // 指定日期加减
                //dayjs().add(7, 'day').format('YYYY-MM-DD');
                //dayjs().subtract(2, 'hour').format('YYYY-MM-DD HH:mm:ss');
                let daysetArray = defaultValList[1].split('-')
                dValue[1] = dayjs()[daysetArray[0]](Number(daysetArray[1]), daysetArray[2]).format(dateFormatStr)
            } else {
                //空日期
                dValue[1] = end
            }
        }
        return dValue
    } catch (error) {
        return [start, end]
    }
}
// 批量设置设置默认为 非默认值
const EditBatch = async () => {
    let _url = `/api/system/Common/EditBatch`
    if (!solutionCID.value || !optionModel.value.searchProSettingCPARENT) {
        return
    }
    let params = {
        "ConnId": "",
        "table": "TBL_SYS_ADVANCED_SEARCH", // 固定参数
        "ModelJson": "{\"CDEFAULT\":false}",
        "where": "CPARENT=" + `'${optionModel.value.searchProSettingCPARENT}' AND CID <> ${solutionCID.value}`
    }
    await axios.request({
        url: _url,
        method: "post",
        data: params,
    }).then(res => {
        if (!!res.Success) {
            // 需要使用 ElMessage 替代 this.$message
            console.log(!!res.Content ? res.Content : '执行成功')
        }
    }).catch(err => {
        console.error('EditBatch error:', err)
    })
}

// 删除高级查询配置信息
const removeConditionClick = () => {
    // 需要使用 ElMessageBox 替代 this.$confirm
    console.log('此操作将删除高级查询配置数据, 是否继续?')
    deleteSolutionItemByCID()
}
// 删除指定的解决方案
const deleteSolutionItemByCID = async () => {
    deleteBtnLoading.value = true
    let _url = `/api/SYSTEM/Common/Remove`

    let params = {
        "table": "TBL_SYS_ADVANCED_SEARCH", // 固定参数
        CID: solutionCID.value // 页面ID
    }
    await axios.request({
        url: _url,
        method: "post",
        data: params,
    }).then(res => {
        if (!!res.Success) {
            deleteBtnLoading.value = false
            // 需要使用 ElMessage 替代 this.$message
            console.log(!!res.Content ? res.Content : '执行成功')
            //  重置数据 当点击清空获取删除动作 需要清空缓存
           // resetData()
            isClearTreeData.value = Math.ceil(Math.random() * 10000)

            // 清空表单字段
            solutionCID.value = null
            Object.assign(formSolution, {
                name: '',
                region: 0,
                defaultOption: false
            })

            // 清除表单验证
            if (searchSolutionRef.value) {
                searchSolutionRef.value.clearValidate()
            }

            // 强制重新查询数据
            loadSolutionList(true)
        }
    }).catch(err => {
        deleteBtnLoading.value = false
        console.error('Delete solution error:', err)
    })
}

// 查询高级查询配置信息
const loadSolutionList = async (forceUpdates = false) => {
    
    //  如果已经有缓存 直接返还
    let cacheSolutionList = getCahceSolutionList()

    if (!forceUpdates && cacheSolutionList && cacheSolutionList.length > 0) {
        tableDataLoading.value = true
        let defaultData = getDefaultSolutionData(cacheSolutionList)
        try {
            let lastTimeSearchSolutionCID = cacheDataObj.value[fullURL].lastTimeSearchSolutionCID
            if(lastTimeSearchSolutionCID){
                 // 从缓存中，获取上次查询的解决方法，如没有采取获取默认查询方案
                  defaultData = filterSolutionByCID(lastTimeSearchSolutionCID)
            }
        } catch (error) {

        }
        if (defaultData) {
            let CCONDITION = JSON.parse(defaultData.CCONDITION)
            // 查询条件
            if (CCONDITION.tableData) {
                tableData.value = setTableDataDefaultValue(CCONDITION.tableData)
            }
            // 查询控件配置参数
            if (CCONDITION.loadDataConfig) {
                loadDataConfig.value = CCONDITION.loadDataConfig
            }

        }
        setTimeout(()=>{
            tableDataLoading.value = false
        },1000)
        return
    }
     tableDataLoading.value = true
    let _url = `/api/SYSTEM/Common/PageQuery`
    let params = {
        "table": "TBL_SYS_ADVANCED_SEARCH", // 固定参数
        "where": "CPARENT=" + `'${optionModel.value.searchProSettingCPARENT}'`
    }
    
    await axios.request({
        url: _url,
        method: "post",
        data: params,
    }).then(res => {
       // debugger
        if (!!res.Success && res.Datas && res.Datas.length > 0) {

            solutionList.value = res.Datas
            // ===========设置缓存 key ：当前路由全名称======
            cacheDataObj.value[fullURL] ={
                solutionList:solutionList.value
            }
           // ===========设置缓存 key ：当前路由全名称======
            let defaultData = getDefaultSolutionData()
            if (defaultData) {

                let CCONDITION = JSON.parse(defaultData.CCONDITION)
                // 查询条件
                if (CCONDITION.tableData) {
                    tableData.value = setTableDataDefaultValue(CCONDITION.tableData)
                }
                // 查询控件配置参数
                if (CCONDITION.loadDataConfig) {
                    loadDataConfig.value = CCONDITION.loadDataConfig
                }
            }

        }
    }).catch(err => {
        console.error('Load solution list error:', err)
    })
    tableDataLoading.value = false
}
// 设置表格数据默认值，默认时间等 ,noCache :强制不使用缓存
const setTableDataDefaultValue = (dataList=[], noCache=false) => {
    // debugger
    let newDefaultDataList = []
    let _cacheSearchParamsObj = getCacheSearchParams()
    if(_cacheSearchParamsObj && !noCache){
        dataList.forEach(newItem=>{
            if(_cacheSearchParamsObj[newItem.id] && _cacheSearchParamsObj[newItem.id].hasOwnProperty("isCheck")){
                newItem.isCheck = _cacheSearchParamsObj[newItem.id].isCheck
            }else{
                newItem.isCheck = true
            }
            newItem.value = _cacheSearchParamsObj[newItem.id].value
            newItem.comparator = _cacheSearchParamsObj[newItem.id].comparator
            newItem.relationSign = _cacheSearchParamsObj[newItem.id].relationSign
            newDefaultDataList.push(newItem)
        })

    }else{
        dataList.forEach(item=>{
         item.isCheck=true // 添加默认字段 并且设置为true,意为是有有效
        if(!!item.defaultValue){
            // 设置普通的默认值
            switch (item.controlType) {
                    case "number":
                    item.value = !!item.defaultValue?Number(item.defaultValue):null
                        break;
                    case "date":
                    case "datetime":
                    item.value = setDateTimeDefaultVal(item.controlType,item.defaultValue)
                    break;
                    case "daterange":
                    case "datetimerange":
                        if(!!item.defaultValue){
                            item.value = setDateTimeRangeDefaultVal(item.controlType,item.defaultValue)
                        }

                    break;
                    default:
                        // 字符串 文本
                        item.value = item.defaultValue
                        break;
                }
        }
        newDefaultDataList.push(item)
    })
    }
    // debugger
    return newDefaultDataList
}
// 获取默认的解决方案，如果没有设置默认的，则使用后台添加初始数据作为默认值
const getDefaultSolutionData = (_solutionList=[]) => {

    if(_solutionList.length==0){
        // 默认值
        _solutionList = solutionList.value
    }
    let defaultItem = null
    // 获取设置了默认值 解决方案
    let filterListBy_CDEFAULT = _solutionList.filter(item => {
        if (!!item.CDEFAULT) {
            currentSolutionCID.value = item.CID
            return item
        }
    })
    if (filterListBy_CDEFAULT && filterListBy_CDEFAULT.length > 0) {
        defaultItem = filterListBy_CDEFAULT[0]
    } else {
        // 如果没有设置默认值，则取系统添加的解决方案
        defaultItem = filterSolutionByCID(optionModel.value.searchProSettingID,_solutionList)
    }
    return defaultItem
}

// 从解决方案列表通过CID 过滤获取
const filterSolutionByCID = (CID, _solutionList=[]) => {
    if(_solutionList.length==0){
         // 默认值
        _solutionList = solutionList.value
    }
    let defaultItem = null
    // 如果没有设置默认值，则取系统添加的解决方案
    let filterListBy_CID = _solutionList.filter(item => {
        if (item.CID == CID) {
            return item
        }
    })
    if (filterListBy_CID && filterListBy_CID.length > 0) {
        defaultItem = filterListBy_CID[0]
    }
    return defaultItem
}

const submitEditDialog = () => {
    // 先验证表单 必填字段
    searchSolutionRef.value.validate((valid) => {
        if (valid) {
            // 直接调用 子控件实例 对应的方法
            let _TableSecondTemplateRef = TableSecondTemplateRef.value
            if (_TableSecondTemplateRef) {
                _TableSecondTemplateRef.submitEditDialog()
            }
        } else {
            // console.log('error submit!!');
            return false;
        }
    });
}

const submitBtnLoadingFn = (val) => {
    submitBtnLoading.value = val
}

const handleClick = (params) => {
    // 处理点击事件
}

// 设置参数对象，方便缓存
const setCacheSearchParams = (_dataList, type='search') => {
   let _searchObj = {}
   _dataList.forEach(item=>{
        let newItem = {
            id:item.id,
            field:item.field,
            isCheck:item.isCheck,
            value:item.value,
            comparator: item.comparator,
            relationSign: item.relationSign,
        }
        _searchObj[item.id]=newItem
   })
   return _searchObj
}

// 获取缓存搜索参数
const getCacheSearchParams = () => {
    try {
        return cacheDataObj.value[fullURL]?.searchParams || null
    } catch (error) {
        return null
    }
}

// 获取缓存解决方案列表
const getCahceSolutionList = () => {
    //debugger
    try {
        return cacheDataObj.value[fullURL]?.solutionList || []
    } catch (error) {
        return []
    }
}

// 重置数据
const resetData = () => {
    // 重置数据逻辑
    cacheDataObj.value[fullURL] = {}
    // solutionList.value = []
    // tableData.value = []
}

// 回车事件 回调 》》查询
const handleEnterEvent = (e) => {
    queryFunc()
}

// 重置查询参数列表
const resetQuery = () => {
    loadSolutionList(true) // 强制刷新
}

// 设置时间默认值
const setDateTimeDefaultVal = (type, defaultVal) => {
    // 实现时间默认值设置逻辑
    return defaultVal
}
// 查询按钮事件
const queryFunc = () => {
    loading_PostSearchBtn.value = true
    clearTimeout(searchTimer.value)
    searchTimer.value = setTimeout(() => {
        let _dataList = getSearchTableData()
        // =======开始设置保存缓存==============
        let _visibleData = getSearchTableData("visibleData")
        let searchParams = setCacheSearchParams(_visibleData)
        // debugger
        cacheDataObj.value[fullURL].searchParams = searchParams
         // =======开始设置保存缓存==============
        // ===========设置缓存 key ：当前路由全名称======
        cacheDataObj.value[fullURL].lastTimeSearchSolutionCID = currentSolutionCID.value
        // ===========设置缓存 key ：当前路由全名称======

        let _ConditionalList = formatConditionalList(_dataList)
        let postConditionalList = [
            {
                ConditionalList: _ConditionalList
            }
        ]
        //let postConditionalList = _ConditionalList

        loading_PostSearchBtn.value = false
        let postData = {
            fullPath: fullURL,
            conditionalList: postConditionalList,//JSON.stringify(postConditionalList)
        }


       // 搜索完毕是否 关闭 当前弹框
       if(!!optionModel.value.closeAfterSearchPro){
            drawerShow.value = false
        }
        // 需要替换 this.$actions.setGlobalState 为适当的全局状态管理
        console.log('setGlobalState:', {
            type: "searchProDrawerBox",
            postData: postData,
        });
        emit('queryFunc', postData)
       // return postConditionalList
    }, 1000)
}
// 格式化查询条件 来适应后台（多条件+多条件组）的功能
// SqlSugar将通用查询封装到支持了树型条件，并且支持所有常用的操作，
// 用SqlSugar或者不用SqlSugar的都可参参考一下
// 默认第一个必须为-1 ：null
const formatConditionalList = (dataList) => {
    let _ConditionalList = []
    dataList.forEach((oldItem,index) => {
        //debugger
        if(!oldItem.isCheck && oldItem.children && oldItem.children.length==0){
            // 如果没有勾选，则无效，不生成
            return
        }
        // 条件 列表
        let FieldValue = oldItem.value
        if (oldItem.controlType == 'reportMulSelect'||oldItem.controlType == 'customMulSelect') {
            // 下拉多选 的值 数组 需要 字符串 [X,Y,Z]==>X,Y,Z
            FieldValue = FieldValue.toString()
        }
        // 条件
        if (oldItem.parentId !=0) {
            // debugger
            // 特殊处理，时间范围区间搜索 转换为  daterange datetimerange  开始时间<=value<=结束时间
            if (oldItem.controlType == 'daterange' || oldItem.controlType == 'datetimerange') {
                let newItem = {
                    "Key": (index==0?-1:oldItem.relationSign),  // 固定 Key表式运算符:   And =0，  Or=1,  null=-1
                    "Value": {
                            "ConditionalList": [
                                {
                                    "Key": 0, //固定 Key表式运算符:   And =0，  Or=1,  null=-1
                                    "Value": {
                                        "FieldName": !!oldItem.tableName?(oldItem.tableName+'.'+oldItem.field):oldItem.field,
                                        "FieldValue": FieldValue[0], //  开始时间
                                        "ConditionalType": 3 //大于等于
                                    }
                                },
                                {
                                    "Key": 0, //固定 Key表式运算符:   And =0，  Or=1,  null=-1
                                    "Value": {
                                        "FieldName": !!oldItem.tableName?(oldItem.tableName+'.'+oldItem.field):oldItem.field,
                                        "FieldValue": FieldValue[1],// 结束时间
                                        "ConditionalType": 5 //小于等于
                                    }
                                }
                            ]
                    }
                }
                if(!!FieldValue && !!FieldValue[0] && !!FieldValue[1]){
                    _ConditionalList.push(newItem)
                }


            } else{
                let newItem = {
                "Key": (index==0?-1:oldItem.relationSign),//oldItem.comparator, // Key表式运算符:   And =0，  Or=1,  null=-1
                "Value": {
                    "FieldName":!!oldItem.tableName?(oldItem.tableName+'.'+oldItem.field):oldItem.field, // 字段名称
                    "FieldValue": FieldValue, // 查询值
                    "ConditionalType": oldItem.comparator // 模糊查询，等于，大于，小于...
                    }
                }

                if(!!FieldValue){
                    _ConditionalList.push(newItem)
                }
            }

        }
        // 条件组
        else if (oldItem.parentId == 0 && oldItem.children.length > 0) {
            let queryList = formatConditionalList(oldItem.children)
            // debugger
            let _PConditionalList = {
                "Key": (index==0?-1:oldItem.relationSign),
                "Value": {
                    "ConditionalList": queryList
                }
            }
            if(queryList && queryList.length>0){
                _ConditionalList.push(_PConditionalList)
            }

        }
    })
    return _ConditionalList
}
// 获取搜索表格查询数据
const getSearchTableData = (dataType='fullData') => {
    let dataList = []
    try {
        let _TableFirstTemplateRef = TableFirstTemplateRef.value?.$refs?.vxeTableRef
        dataList = _TableFirstTemplateRef.getTableData()[dataType]

    } catch (error) {
        return dataList
    }
    return dataList
}

// 下拉框数据请求
const dropdBownBox = (val) => {
    // 下拉框数据请求逻辑
}

// 新增组, 新增条件
const addProgramme = (val) => {
    //debugger
    isTure.value = true
    addFlag.hash = Math.ceil(Math.random() * 10000);
    addFlag.flag = val
}

// 清空内容
const clearClick = () => {
    //  重置数据 当点击清空获取删除动作 需要清空缓存
    resetData()
    isClearTreeData.value = Math.ceil(Math.random() * 10000)

    // 清空表单字段
    solutionCID.value = null
    Object.assign(formSolution, {
        name: '',
        region: 0,
        defaultOption: false
    })

    // 清除表单验证
    if (searchSolutionRef.value) {
        searchSolutionRef.value.clearValidate()
    }
}

const addClick = () => {
    isAdd.value = true
    isTure.value = false
}

// 关闭弹框,清理动作
const closeDrawer = () => {
    submitBtnLoading.value = false
    tableDataLoading.value = false
    emit('update:drawerShow', false)
   // emit('queryFunc', formSolution)
    Object.assign(formSolution, {
        name: '',
        region: 0,
        defaultOption: false
    })
}

const cancelClick = () => {
    closeClick()
}

// 方案切换 回调事件
const handleCommand = (val_CID) => {
    currentSolutionCID.value = val_CID
    let defaultData = filterSolutionByCID(val_CID)
    if (defaultData) {
        let CCONDITION = JSON.parse(defaultData.CCONDITION)
        // 查询条件
        if (CCONDITION.tableData) {
            tableData.value = setTableDataDefaultValue(CCONDITION.tableData,true)
        }
        // 查询控件配置参数
        if (CCONDITION.loadDataConfig) {
            loadDataConfig.value = CCONDITION.loadDataConfig
        }
    }
}

// 方案切换 回调事件【新增方案页面】
const handleNewCommand = (val_CID) => {
    // 移除表单项的校验结果
    searchSolutionRef.value.clearValidate()
    solutionCID.value = val_CID

    // 获取选中的方案信息并填充到表单
    const selectedSolution = filterSolutionByCID(val_CID)
    if (selectedSolution) {
        // 将方案信息赋值到对应的输入框
        formSolution.name = selectedSolution.CSCHEME_NAME || ''
        formSolution.region = selectedSolution.CVISIBLE || 0
        formSolution.defaultOption = !!selectedSolution.CDEFAULT
    }

    // 直接调用 子控件实例 对应的方法
    let _TableSecondTemplateRef = TableSecondTemplateRef.value
    if (_TableSecondTemplateRef) {
        _TableSecondTemplateRef.solutionCID_change(val_CID)
    }
}

const editActivedEvent = () => {
    // 编辑激活事件
}

// 需要添加一些缺失的方法
const closeClick = () => {
    closeDrawer()
}

const formDataChangeFn = (data) => {
    // 表单数据变化回调
}

const disabledDeleteBtnFn = (disabled) => {
    isDisabledDeleteBtn.value = disabled
}

const submitSuccessFn = (data) => {
    // 提交成功回调
    loadSolutionList(true) // 重新加载方案列表
    // 重置表单
    Object.assign(formSolution, {
        name: '',
        region: 0,
        defaultOption: false
    })

}

// 暴露给父组件的方法
defineExpose({
    openDrawer,
    queryFunc,
    resetQuery,
    closeDrawer
})
</script>
<style lang='scss' scoped>
  .drawerClass {
    
    :deep(.el-drawer__header)  {
        align-items: center;
        color: #72767b;
        display: flex;
        height: 39px;
        padding: 5px 10px;
        border-bottom: 1px solid #dcdfe6 !important;
        margin-bottom: 10px !important;
    }
     :deep(.el-tabs__header)  {
        margin: 0px !important;
    }


  /*  .dropDownCla {
        @apply flex items-center px-2.5 py-1.5 mr-2.5 bg-blue-500 rounded text-center cursor-pointer;
    }

    .dropdownLink {
        @apply inline-block text-white w-full px-1.5 text-left;
        font-size: 12px !important;

        i {
            @apply mr-1;
        }
    }*/
}
</style>
